﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Seven.DataModel.RepositoryModels.RoleAbout;
using Seven.DataModel.ViewModels.RoleAbout;
using Seven.Tools.Extension;
using Seven.Web.IntelligentQuery.Extensions;

namespace Seven.MsSql.Repositories
{
    public partial class SysRoleRepository
    {
        #region 获取简单模型数据

        /// <summary>
        /// 根据公司ID获取其拥有的角色集合的简单数据模型
        /// </summary>
        /// <param name="companyId">公司ID</param>
        /// <param name="includeDisabled">是否包含已禁用的角色</param>
        /// <returns></returns>
        public IEnumerable<SimpleModel1> GetSimpleModelByCompanyID(int companyId, bool includeDisabled)
        {
            var query = this.Entities().Where(w => w.CompanyID == companyId && !w.IsDeleted && !w.IsSuperAdmin);
            if (!includeDisabled) { query = query.Where(w => !w.IsDisabled); }
            var data = query.OrderBy(o => o.SortNumber).Select(s => new { s.ID, s.Name, s.Icon, s.IsDisabled }).ToArray();

            return data.Select(s => s.CastTo<SimpleModel1>());
        }

        #endregion

        /// <summary>
        /// 根据角色ID获取供编辑的数据模型
        /// </summary>
        /// <param name="id">角色ID</param>
        /// <returns></returns>
        public RoleModel GetEditModelByID(int id)
        {
            var role = this.Entities().Where(w => w.ID == id);
            var company = new HrOrganizationRepository(this.dbContext).Entities();

            var query = (from a in role
                         join b in company on a.CompanyID equals b.ID
                         select new
                         {
                             a.ID,
                             a.Name,
                             a.Code,
                             a.SortNumber,
                             a.Icon,
                             a.IsDisabled,
                             a.Remark,
                             a.CompanyID,
                             CompanyName = b.Name
                         }).FirstOrDefault();

            return query.CastTo<RoleModel>();
        }

        /// <summary>
        /// 获取角色管理列表数据
        /// </summary>
        /// <param name="companyId">公司ID</param>
        /// <param name="model">序列化的查询条件</param>
        /// <param name="page">页码</param>
        /// <param name="rows">每页条数</param>
        /// <returns></returns>
        public IEnumerable<RoleGridModel> RoleManageGrid(int? companyId, string model, int page, int rows)
        {
            var role = this.Entities().Where(w => !w.IsDeleted);
            var user = new SysUserRepository(this.dbContext).Entities();
            var staff = new HrStaffRepository(this.dbContext).Entities();
            var company = new HrOrganizationRepository(this.dbContext).Entities();

            var dicModel = new Dictionary<string, string>();
            var queryModel = this.ConvertQueryModel(model, ref dicModel);
            if (queryModel != null) { role = role.Where(queryModel); }

            #region 查询条件组织

            if (companyId.HasValue)
            {
                role = role.Where(w => w.CompanyID == companyId.Value);
            }

            #endregion

            var query = (from a in role
                         join b in company on a.CompanyID equals b.ID
                         join c in user on a.DisableUserName equals c.UserName into ac
                         from DisablerInfo1 in ac.DefaultIfEmpty()
                         join d in staff on DisablerInfo1.StaffID equals d.ID into ad
                         from DisablerInfo2 in ad.DefaultIfEmpty()
                         select new
                         {
                             a.ID,
                             a.Name,
                             a.Code,
                             a.SortNumber,
                             CompanyName = b.Name,
                             a.Icon,
                             a.IsDisabled,
                             DisableRealName = DisablerInfo2 == null ? "" : DisablerInfo2.RealName,
                             a.DisableDate
                         });

            var result = query.OrderBy(o => o.SortNumber).SplitPage(page - 1, rows).ToArray();

            return result.Select(s => s.CastTo<RoleGridModel>(false));
        }

        /// <summary>
        /// 获取指定公司的角色列表数据
        /// </summary>
        /// <param name="companyId">公司ID</param>
        /// <param name="name">角色名字</param>
        /// <returns></returns>
        public IEnumerable<SimpleModel1> RoleGrid(int companyId, string name)
        {
            var query = this.Entities().Where(w => w.CompanyID == companyId && !w.IsDisabled && !w.IsSuperAdmin && !w.IsDeleted);
            if (!string.IsNullOrWhiteSpace(name)) { query = query.Where(w => w.Name.Contains(name)); }

            var data = query.OrderBy(o => o.SortNumber).Select(s => new{ s.ID, s.Name, s.Icon }).ToArray();

            return data.Select(s => s.CastTo<SimpleModel1>(false));
        }

        /// <summary>
        /// 根据公司ID集合，获取他们的下属角色的数量，以Dic形式返回数据，其中Key为ids的元素，Value为其拥有的角色数量
        /// </summary>
        /// <param name="ids">公司ID集合</param>
        /// <returns></returns>
        public IDictionary<int, int> GetRolesCountByCompanyIDs(IEnumerable<int> ids)
        {
            var result = new Dictionary<int, int>();
            if (ids.Count() == 0) { return result; }
            var data = this.Entities()
                .Where(w => !w.IsSuperAdmin && !w.IsDisabled && !w.IsDeleted && ids.Contains(w.CompanyID))
                .GroupBy(g => g.CompanyID)
                .Select(s => new { s.Key, Value = s.Count() });
            foreach (var item in data)
            {
                result.Add(item.Key, item.Value);
            }

            return result;
        }
    }
}
